package edu.gatech.cc.hwa.server.security.encryption;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.spec.SecretKeySpec;

import edu.gatech.cc.hwa.server.security.exceptions.HwaSecurityException;
import edu.gatech.cc.hwa.server.security.StringByteArrayConverter;

public class KeyConverter {
	
	public static SecretKeySpec stringToAesKey(String key) throws HwaSecurityException {
		return new SecretKeySpec(createTruncatedPasswordHash(key), EncryptionSettings.ENCRYPTION_ALGORITHM);
	}

	public static byte[] createTruncatedPasswordHash(String text) throws HwaSecurityException {
		return Arrays.copyOf(createFullLengthPasswordHash(text), 16);
	}

	public static byte[] createFullLengthPasswordHash(String text) throws HwaSecurityException {
		try {
			MessageDigest md = MessageDigest.getInstance(EncryptionSettings.MD_ALGORITHM);
			md.update(StringByteArrayConverter.convertToByteArray(text), 0, text.length());
			return md.digest();
		} catch(NoSuchAlgorithmException e) {
			throw new HwaSecurityException(e);
		}
	}
}
